package com.cast.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cast.health.entity.PageResult;
import com.cast.health.entity.QueryPageBean;
import com.cast.health.mapper.SetmealMapper;
import com.cast.health.pojo.Setmeal;
import com.cast.health.service.CheckGroupService;
import com.cast.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private CheckGroupService checkGroupService;

    @Override
    public boolean addSetmeal(Setmeal setmeal,Integer[] checkgroupIds) {
        if (setmeal == null) {
            return false;
        }

        //根据code属性条件查询,判断该条数据是否已经存在
        LambdaQueryWrapper<Setmeal> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getCode,setmeal.getCode());
        Setmeal one = this.getOne(wrapper);
        //判断是否存在该套餐对象
        if (one != null) {//代表该项目组存在,则不需要添加
            return false;
        }
        //添加套餐信息到套餐表
       this.save(setmeal);
        //得到套餐id设置到中间表
        Integer id = setmeal.getId();
        //添加中间表信息:套餐和套餐id设置到中间表
        //添加一个套餐对应可能有多个检查组,循环遍历所有检查组给到mapper
        for (int i = 0; i < checkgroupIds.length; i++) {
            setmealMapper.setSetmealAndCheckGroup(id,checkgroupIds[i]);
        }

        return true;
    }


    @Override
    public PageResult findPageSetmeal(QueryPageBean queryPageBean) {
        //获取分页条件
        Integer page = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String name = queryPageBean.getQueryString();

        //分页工具对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        //条件查询
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        //当存在条件
        if (name != "" && null != name) {
            //String trim = name.trim();
            wrapper.like(Setmeal::getCode, name).or().
                    like(Setmeal::getName, name).or().
                    like(Setmeal::getHelpCode, name);
        }

        //根据从值升序排序
        wrapper.orderByAsc(Setmeal::getCode);

        Page<Setmeal> setmealIPage = setmealMapper.selectPage(pageInfo, wrapper);
        if (setmealIPage==null){
            return null;
        }
        return new PageResult(setmealIPage.getTotal(), setmealIPage.getRecords());
    }
}
